local dangju = fk.CreateSkill {
  name = "ls__dangju",
}

local ls = require "packages/lvshi/utility"

Fk:loadTranslationTable{
  ["ls__dangju"] = "宕局",
  [":ls__dangju"] = "回合技，己方角色的手牌变为最少后，你可选择一项：1.将一张锦囊牌当【增兵减灶】对其使用；2.此轮不能发动此技能，此轮结束时视为对其使用【增兵减灶】。",
  ["#dangju-choose"] = "宕局：选择一项",
  ["#dangju-trick"] = "宕局：将一张锦囊牌当【增兵减灶】对手牌变为最少的己方角色使用",
  ["#dangju-delay"] = "此轮不能发动此技能，此轮结束时视为对这些角色使用【增兵减灶】",
  ["@[player]dangju-round"] = "宕局",
}

-- 获取己方手牌最少的角色组
local function getMinHandcardAllies(player)
  local min_cards = math.huge
  local allies = {}
  
  for _, p in ipairs(player.room.alive_players) do
    local hand_num = p:getHandcardNum()
    if hand_num < min_cards then
      min_cards = hand_num
      allies = {p}
    elseif hand_num == min_cards then
      table.insert(allies, p)
    end
  end
  
  return allies, min_cards
end

-- 监听手牌变化事件
dangju:addEffect(fk.AfterCardsMove, {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(dangju.name) or #player:getTableMark("@[player]dangju-round") > 0
    or player:usedSkillTimes(dangju.name) > 0 then return end
    local min_allies, old_min_cards = getMinHandcardAllies(player)
    
    for _, move in ipairs(data) do
      -- 情况1：角色失去手牌后，其手牌从场上不是最少变为为场上最少
      if move.from and ls.isFriend(player, move.from) then
        local from = move.from
        local ishandcard = false
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            ishandcard = true
          end
        end 
        if ishandcard then
          local from_old_hand = from:getHandcardNum() + #move.moveInfo
          if from_old_hand > old_min_cards and from:getHandcardNum() == old_min_cards then
            event:setCostData(self, {targets = {from}})
            return true
          end
        end
      end
      
      -- 情况2：角色获得手牌后，其手牌从场上最少变为场上不是最少，且手牌数最小的角色为己方角色
      if move.to and move.toArea == Card.PlayerHand and ls.isFriend(player, move.to) then
        local to = move.to
        local to_old_hand = to:getHandcardNum() - #move.moveInfo
        -- 检查移动后to的手牌是否大于old_min_cards
        if to_old_hand <= old_min_cards and to:getHandcardNum() > old_min_cards then
          local friends = table.filter(min_allies, function (p) return ls.isFriend(player, p) end)
          if #friends > 0 then
            event:setCostData(self, {targets = friends})
            return true
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local targets = event:getCostData(self).targets
    local tos, cards = player.room:askToChooseCardsAndPlayers(player, {
      targets = targets,
      min_num = 1,
      max_num = #targets,
      min_card_num = 1,
      max_card_num = 1,
      pattern = ".|.|.|.|.|trick",
      prompt = "#dangju-trick",
      skill_name = dangju.name,
    })
    if #tos > 0 and #cards > 0 then
      event:setCostData(self, {subcards = cards, use_tos = tos})
      return true
    elseif player.room:askToSkillInvoke(player, {skill_name = dangju.name, prompt = "#dangju-delay"}) then
      event:setCostData(self, {delay = targets})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event:getCostData(self).subcards and event:getCostData(self).use_tos then
      room:useVirtualCard("reinforcement", event:getCostData(self).subcards, player, event:getCostData(self).use_tos, dangju.name, true)
    elseif event:getCostData(self).delay and #event:getCostData(self).delay > 0 then
      room:setPlayerMark(player, "@[player]dangju-round", table.map(event:getCostData(self).delay, Util.IdMapper))
    end
  end,
})

dangju:addEffect(fk.RoundEnd, {
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(dangju.name, true) and #player:getTableMark("@[player]dangju-round") > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(player:getTableMark("@[player]dangju-round"), Util.Id2PlayerMapper)
    room:useVirtualCard("reinforcement", nil, player, targets, dangju.name, true)
  end,
})

return dangju